package com.sun.gis.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.util.ArrayList;
import java.util.List;

@Api(tags = "地图切片访问接口")
@RestController
@RequestMapping("/tiles")
public class TilesController {

    private static final String BASE_PATH = "D:\\data\\tmsData";

    @ApiOperation(value = "切片访问接口", notes = "根据token访问本地切片")
    @GetMapping("/{z}/{x}/{y}.png")
    public ResponseEntity<?> getTile(
            @PathVariable int z,
            @PathVariable int x,
            @PathVariable int y,
            @RequestParam String token) {

        // 获取Token的访问权限
        List<String> accessRegions = new ArrayList<>();
        accessRegions.add("320205_202202");
        accessRegions.add("3212");
        if (accessRegions.isEmpty()) {
            return ResponseEntity.status(HttpStatus.FORBIDDEN).body("Access Denied");
        }

        // 构造文件路径并检查访问权限
        for (String region : accessRegions) {
            File tileFile = new File(BASE_PATH + File.separator + region + File.separator + z + File.separator + x + File.separator + y + ".png");
            if (tileFile.exists()) {
                try {
                    byte[] imageBytes = Files.readAllBytes(tileFile.toPath());
                    return ResponseEntity.ok().contentType(MediaType.IMAGE_PNG).body(imageBytes);
                } catch (IOException e) {
                    return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Error Reading Tile");
                }
            }
        }

        return ResponseEntity.status(HttpStatus.NOT_FOUND).body("Tile Not Found");
    }

}
